package com.ophiux.wechat.servlet.code;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ophiux.wechat.db.AUTH_MAP;
import com.ophiux.wechat.db.MchAppModel;

/**
 * code授权地址入口
 * @author chenh
 * wechatpay.ophiux.com/OphiuxWeChatPayPlatformbuild/RedirectServlet?appid=wx4a81b91ffb2bb6ed
 * &appsecret=D310d5f9a57bbb8ff3ebd9597beacd554&client_back_url=null

wechatpay.ophiux.com/OphiuxWeChatPayPlatformbuild/OauthServlet?appid=wx4a81b91ffb2bb6ed&appsecret=D310d5
f9a57bbb8ff3ebd9597beacd554&client_back_url=null
 *http://wechatpay.ophiux.com/OphiuxWeChatPayPlatformbuild/RedirectServlet?orderno=&money=&submchid=&
 */
public class CodeOauthServlet extends HttpServlet {
	
	private static Logger logger = LoggerFactory.getLogger(CodeOauthServlet.class);

	private String REDIRECT_URL ="http://wechatpay.ophiux.com/OphiuxWeChatPayPlatformbuild/CodeRedirectServlet";
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 
		/**
		 * 2017-11-30 sqx 
		 * 取消前端 明文传递appid，appsecret 
		 * 使用token 获取商户信息
		 */
		/*String appid = request.getParameter("appid");
		String appsecret = request.getParameter("appsecret");*/
		String token = request.getParameter("token");
		String scope = request.getParameter("scope");
		
		MchAppModel mchApp = AUTH_MAP.getAppModelByToken(token);
		
		String appid = mchApp.getAppid();
		String appsecret = mchApp.getAppsecret();
		
		
		/**
		 * 回调至终端页面
		 */
		String client_back_url = request.getParameter("client_back_url");
		
		String backUri = REDIRECT_URL;
		
 		backUri = backUri+"?client_back_url="+client_back_url+"";
 	 	backUri = URLEncoder.encode(backUri);
		logger.info("REDIRECT_URL(code回调地址):"+backUri);
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
				"appid=" + appid+
				"&redirect_uri=" +
				 backUri+
				"&response_type=code&scope="+scope+"&state=123#wechat_redirect";
		System.out.println("url="+url);
		logger.info("接收到终端授权请求，授权链接为："+url);
		//重定向
		response.sendRedirect(url);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	
}
